package com.bobi.tfca.ui.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.databinding.RowReceivedMessageLayoutBinding
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.ui.mainnavigation.message.chatroom.ChatRoomFragment
import com.bobi.tfca.util.LogUtil
import com.bumptech.glide.Glide
import java.util.ArrayList

class MessageAdapter(
    val fragment: ChatRoomFragment,
    val memberId: Int,
    var messageResponseList: ArrayList<MessageResponse>
) :
    RecyclerView.Adapter<MessageAdapter.MessageViewHolder>() {


    inner class MessageViewHolder(private val binding: RowReceivedMessageLayoutBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(message: MessageResponse) {
            val url = message.senderPicture
            if (message.isTimeVisible) {
                binding.timestamp.visibility = View.VISIBLE
            }
            // 如果是自己发的信息
            LogUtil.i("messagerId::$memberId, senderId::${message.senderId}, content::${message.content}")
            if (memberId == message.senderId) {
                binding.rlOtherSent.visibility = View.GONE
                binding.rlMySent.visibility = View.VISIBLE
                if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                    Glide.with(fragment).load(url).placeholder(R.mipmap.default_avatar).into(binding.ivMyUserhead)
                }
            } else {
                binding.rlOtherSent.visibility = View.VISIBLE
                binding.rlMySent.visibility = View.GONE
                if (url != null && url.isNotBlank() && (!"null".equals(url))) {
                    Glide.with(fragment).load(url).placeholder(R.mipmap.default_avatar).into(binding.ivUserhead)
                }
            }
            binding.message = message
        }
    }

    fun setItemList(chatRoomList: ArrayList<MessageResponse>) {
        this.messageResponseList = chatRoomList
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MessageViewHolder {
        val itemView = RowReceivedMessageLayoutBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        val viewHolder = MessageViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = messageResponseList.size

    override fun onBindViewHolder(holder: MessageViewHolder, position: Int) {
        val message = messageResponseList[position]
        with(holder) {
            bind(message)
        }
        Log.d("Adapter", "Binding message at position $position: ${message.content}")
    }
}